'use strict';
const extend = require('extend');
const logger = require('log4js').getLogger("sys");

const CommonService = require("../../service/util/dbService");
const Model = require("../../module/officialAccount/TagModel");

const TagTypeService = require('./TagTypeService');

const defaultParams = {
    model : Model,
    basePath: '/tag',
};

class ModuleService extends CommonService{
    constructor(param){
        super(param);
        this.opts = extend(true, {}, this.opts, defaultParams, param);
        this._name = "TagService";
    }

    saveWithWX(curUser, officialAccount, data){
        return new Promise((resolve, reject) => {
            officialAccount.createTag(data.name).then(ret => {
                let result = eval(ret);
                if (!result.tag) {
                    reject({message: result.errmsg});
                } else {
                    data.wechat_id = result.tag.id;

                    this.save(curUser, data)
                        .then(
                            saveResult => resolve(saveResult),
                            err => reject(err)
                        );
                }
            }, err => {
                reject({message: err.errmsg});
            });
        });
    }
    updateWithWXById(curUser, officialAccount, id, data){
        return new Promise((resolve, reject) => {
            this.findById(curUser, id).then(tag => {
                let updateLocal = () => {
                    this.updateById(curUser, id, data).then(
                        data => resolve(data),
                        err => reject(err)
                    )
                }
                if(tag.name == data.name){
                    updateLocal();
                }else{
                    officialAccount.updateTag(data.wechat_id, data.name).then(
                        ret => updateLocal(),
                        err => reject(err)
                    )
                }
            }, err => reject(err));
        });
    }
    removeWithWXById(curUser, officialAccount, id){
        let CustomerService = require('./CustomerService');
        return new Promise((resolve, reject) => {
            TagTypeService.findOne(curUser, {defaultTag: id}).then(isDefault => {
                if(isDefault){
                    reject({message: '此类型的默认标签不能删除'});
                }else{
                    this.findById(curUser, id).then(tag => {
                        let deleteTag = () => {
                            //删除官方标签
                            officialAccount.deleteTag(tag.wechat_id).then(wxDelTagRet => {
                                //删除用户身上的标签
                                CustomerService.update(curUser, {tags:id}, {'$pull':{tags:id}}).then(loDelRefRet => {
                                    //删除本地标签
                                    this.removeById(curUser, id).then(
                                        result => resolve(result),
                                        err => reject(err)
                                    );
                                }, err => reject(err));
                            }, err => reject(err));
                        };
                        //判断是否需要添加默认标签
                        if(tag.type){
                            TagTypeService.findById(curUser, tag.type, 'defaultTag').then(thisType => {
                                if(thisType.defaultTag){
                                    CustomerService.batchTagWithWX(curUser, officialAccount, {tags:id}, thisType.defaultTag).then(
                                        localResult => deleteTag(),
                                        err => reject(err)
                                    );
                                }else{
                                    deleteTag();
                                }
                            })
                        }else{
                            deleteTag();
                        }
                    }, err => reject(err))
                }
            }, err => reject(err));
        });
    }
    sync(curUser, officialAccount){
        return new Promise((resolve, reject) => {
            officialAccount.getTagList().then(result => {
                let condition_wechat_id = [];
                let condition = {wechat_id : {'$in':condition_wechat_id}, officialAccount:officialAccount.opts._id};

                if(result.tags.length > 0){
                    let tags = result.tags;

                    tags.forEach(function (tag) {
                        condition_wechat_id.push(tag.id);
                    });

                    this.find(curUser, condition).then(hereTags => {
                        let i;
                        for(i = 0; i < tags.length; ){
                            let flag = hereTags.find(function (customer) {
                                return customer.wechat_id == tags[i].id;
                            });
                            if(flag){
                                tags.splice(i, 1);
                            }else{
                                tags[i].code = tags[i].id;
                                tags[i].wechat_id = tags[i].id;
                                tags[i].officialAccount = officialAccount.opts._id;
                                i++;
                            }
                        }

                        this.create(curUser, tags).then(
                            result => resolve({count : tags.length}),
                            err => reject(err)
                        );
                    }, err => reject(err));
                }else{
                    resolve({count : 0});
                }
            }, err => reject(err));
        });
    }
}

let thisService = new ModuleService();
module.exports = thisService;



